package com.github.codemperor.gateway.fitler;

import com.github.codemperor.api.base.IBaseApi;
import com.github.codemperor.core.token.CurrentUserInfo;
import com.github.codemperor.gateway.config.BaseFilter;
import com.github.codemperor.gateway.config.ZuulConstants;
import com.github.codemperor.gateway.context.FilterContext;
import com.netflix.zuul.context.RequestContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

/**
 * @description 这里设置所有经过网关的请求号和请求节点
 * @Author codemperor
 */
@Component
@Slf4j
public class InitFilter extends BaseFilter {

    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return ZuulConstants.INIT_FILTER;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {

        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();

        //初始化所有的过滤器是否启动
        initAllFilter(request);

        //获取基本信息
        String remoteHostAddress = getRemoteAddress(request);
        String uri = request.getRequestURI();
        String method = request.getMethod();

        //生成网关请求号与节点号 todo 生成方式需要修改
        String requestNo = UUID.randomUUID().toString();
        String spanId = UUID.randomUUID().toString();

        //设置ThreadLocal，向后方filter传递
        CurrentUserInfo user = new CurrentUserInfo();
        user.setRemoteHostAddress(remoteHostAddress);
        user.setUri(uri);
        user.setMethod(method);
        user.setRequestNo(requestNo);
        user.setSpanId(spanId);
        //这里父节点就是本身
        user.setParentSpanId(spanId);

        log.debug("[InitFilter] user: {} ", user);
        FilterContext.currentUserInfo.set(user);
        FilterContext.costMillis.set(System.currentTimeMillis());
        return null;
    }

    private String getRemoteAddress(HttpServletRequest request) {
        // 获取真实ip(阿里云负载均衡设置可以获取用户真实ip，从X-Forwarded-For获取)
        String hostAddress = request.getHeader("X-Forwarded-For");
        if (!StringUtils.isEmpty(hostAddress)) {
            log.debug("[InitFilter] slb ip: {}", hostAddress);
            return hostAddress;
        }

        hostAddress = request.getRemoteAddr();
        log.debug("[InitFilter] getRemoteAddr ip: {}", hostAddress);
        return hostAddress;
    }

    private void initAllFilter(HttpServletRequest request) {
        String uri = request.getRequestURI();
        apiRoleAndTokenFilterEnabled(false);
        FilterContext.websiteTokenFilterEnabled.set(false);

        if (uri.startsWith(IBaseApi.FRONTEND_API_PREFIX + "/")) { //如果是开放接口，取消所有api的校验
            apiRoleAndTokenFilterEnabled(false);
            FilterContext.websiteTokenFilterEnabled.set(false);
        }

        if (uri.startsWith(IBaseApi.FRONTEND_AUTHORIZED_API_PREFIX + "/")) { //前端部分api需要校验
            FilterContext.websiteTokenFilterEnabled.set(true);
        }

        if (uri.startsWith(IBaseApi.CRM_API_PREFIX + "/")) { //开启后台管理系统api校验
            apiRoleAndTokenFilterEnabled(true);
        }

        //处理非正常的可以通过的url请求,这些请求不需要进行过滤
//        if (uri.contains("v2/api-docs") //swagger
//            || uri.contains("/auth/admin/login") //登陆pass
//        ) {
//            apiRoleAndTokenFilterEnabled(false);
//        }
    }

    private void apiRoleAndTokenFilterEnabled(boolean enabled) {
        FilterContext.apiFilterEnabled.set(enabled);
        FilterContext.tokenFilterEnabled.set(enabled);
    }
}
